package travianBot.botScripts;

import java.io.IOException;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

import travianBot.LinkMaker;
import travianBot.ResourceEntry;
import travianBot.TravianBot;
import travianBot.TravianBotException;
import travianBot.Village;

public class ArmoryScript extends TravianScript {

	public String troopToUpgrade; 
	
	static Logger log=Logger.getLogger(ArmoryScript.class);
	
	public ArmoryScript(String cvsString){
		init(cvsString);
	}
	
	@Override
	public void init(String cvsString) {
		//format:position,<village name>,<script type>,
		String[] tokens = cvsString.split(",");
		
		int cursorToken 		= Integer.parseInt(tokens[0]);
		String villageNameToken = tokens[1];
		String typeToken 		= tokens[2];
		String troopToUpgradeToken 	= tokens[3];
		
		this.cursorPosition = cursorToken;
		this.villageName = villageNameToken;
		this.type = typeToken;
		this.troopToUpgrade = troopToUpgradeToken;
		
		log.debug("creating resource script from: "+cvsString);		
	}

	@Override
	public void runScript(TravianBot travianBot,
			HashMap<String, String> sessionInfoMap) throws TravianBotException {
		
		//initialise
		Village village = travianBot.loadVillage(this.villageName);
		if(village == null){
			throw new TravianBotException("Village:"+this.villageName+" does not exist");
		}
		// load the buildings page
		String buildingsPage = travianBot.getHttpContents(LinkMaker.BUILDINGS_PAGE);
		village.initialiseBuildings(buildingsPage);
		
		// get the specific buildings details	
		ResourceEntry resourceEntry = village.getBuildingResourceEntry(Village.ARMORY);		
		
		if(resourceEntry != null){
			// fetch the page for the armory
			String armoryLink = LinkMaker.getBuildingPageLink(resourceEntry);
			String htmlContents = null;
			try {
				htmlContents = travianBot.getHttpContents(armoryLink);
			} catch (Exception e) {	
				log.error("unable to fetch the Armory page");
				throw new TravianBotException("nable to fetch the Armory page", e);
			}
			
			String upgradeLink = null;
			// parse the armory page for the upgrade link
			if(htmlContents != null){
				upgradeLink = getUpgradeLink(htmlContents, this.troopToUpgrade);
			}
			if(upgradeLink != null){
				upgradeLink = LinkMaker.completeRelativeLink(upgradeLink);
				String upgradedPage = travianBot.getHttpContents(LinkMaker.BUILDINGS_PAGE);
				log.debug(upgradedPage);
			}else{
				log.error("Problems upgrading the:"+this.troopToUpgrade+" in village:"+this.villageName);
			}
		}	
	}
	
	public static String getUpgradeLink(String htmlContents, String troopTypeWanted) throws TravianBotException{
		String returnString = null;
		TroopUpgradeLinkReturn returnDetails = new TroopUpgradeLinkReturn();
		HtmlCleaner htmlCleaner = new HtmlCleaner();
		
		try {
			TagNode node = htmlCleaner.clean(htmlContents);
			Object[] nodeArray = node.evaluateXPath("//table[@class='build_details']");
			
			if(nodeArray == null || nodeArray.length <0){
				throw new TravianBotException("problems parsing the Armory web page");
			}
			TagNode tableNode = (TagNode)nodeArray[0];
			Object[] linkArray = tableNode.evaluateXPath("//a");
						
			if(nodeArray == null || nodeArray.length <0){
				throw new TravianBotException("problems parsing the Armory web page - no links in the table");
			}
			
			// collect all of the links.  They'll be paired into description and upgrade
			TagNode anchorTag;
			TagNode upgradeAnchorTag;
			for (int i = 0; i < linkArray.length; i++) {
				anchorTag = (TagNode)linkArray[i];
				TagNode[] contentArray =null ;//= anchorTag.getText();
				String troopType = anchorTag.getText().toString();
	
				if(troopType.equals(troopTypeWanted)){
					// found the right row in the table
					
					if((linkArray.length < i+1) && (upgradeAnchorTag = (TagNode)linkArray[i+1]) != null){
						// hopefully the next anchor tag is for upgrading
						String anchorText = upgradeAnchorTag.getText().toString();
						
						if(anchorText.equals("Improve")){
							returnString = upgradeAnchorTag.getAttributeByName("href");
							break;
						}
					}
				}				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			throw new TravianBotException("problems getting upgrade link", e);
		} catch (XPatherException e) {
			e.printStackTrace();
			throw new TravianBotException("xpath problems getting upgrade link", e);
		}
		return returnString;
	}

}
